package com.up360.rapidcalc.common.util
{
    import flash.display.Loader;
    import flash.events.ErrorEvent;
    import flash.events.Event;
    import flash.events.IOErrorEvent;
    import flash.net.URLLoader;
    import flash.net.URLRequest;
    import flash.net.URLVariables;

    /**
     * @author Tunie
     * @date   May 2, 2013
     */
    public class IOHelper
    {
        public function IOHelper()
        {
        }
        
        /**
         *向服务端发送请求,适用于服务端返回json数据的形式。 
         * @param compOpe
         */
        public static function request(url:String,vals:URLVariables,requestComp:Function,requestError:Function):void
        {
            var b_loader:URLLoader=new URLLoader();
            b_loader.addEventListener(Event.COMPLETE,loadComp);
            b_loader.addEventListener(IOErrorEvent.IO_ERROR,loadError);
            
            var b_request:URLRequest=new URLRequest(url);
            b_request.data=vals;
            b_loader.load(b_request);
            
            function loadComp(e:Event):void
            {
                loadClear();
                requestComp(JSON.parse(b_loader.data));
            }
            
            function loadError(event:IOErrorEvent):void
            {
                loadClear();
                requestError();
            } 
            
            function loadClear():void
            {
                b_loader.removeEventListener(Event.COMPLETE,loadComp);
                b_loader.removeEventListener(IOErrorEvent.IO_ERROR,loadError);
            }
        }
        
        public static function loadPic(url:String,loadPicComp:Function,loadPicError:Function):void
        {
            var b_loader:Loader=new Loader();
            b_loader.contentLoaderInfo.addEventListener(Event.COMPLETE,loadComp);
            b_loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR,loadError);
            
            var b_request:URLRequest=new URLRequest(url);
            b_loader.load(b_request);
            
            function loadComp(e:Event):void
            {
                loadClear();
                loadPicComp(b_loader);
            }
            function loadError(event:IOErrorEvent):void
            {
                loadClear();
                loadPicError();
            }
            function loadClear():void
            {
                b_loader.contentLoaderInfo.removeEventListener(Event.COMPLETE,loadComp);
            }
        }
        
    }
}